package com.xm.dao.impl;

import com.xm.dao.FavoritesDao;
import com.xm.po.Favorites;
import com.xm.util.DButil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Administrator
 * @date 2020-08-07-15:10
 * @description 商品收藏夹数据操作接口实现类
 */
public class FavoritesDaoImpl implements FavoritesDao {
    @Override
    public List<Favorites> getAll(Integer userId) {
        Connection conn = DButil.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Favorites> list = new ArrayList<>();
        String sql = "select * from favorites where userId = ? order by createTime desc";
        try {
            ps = conn.prepareStatement(sql);
            ps.setObject(1,userId);
            rs = ps.executeQuery();
            list = (List<Favorites>) DButil.getRsData(Favorites.class,rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DButil.close(rs,ps,conn);
        }
        return list;
    }

    @Override
    public Favorites check(Integer goodsId, Integer userId) {
        Connection conn = DButil.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        Favorites favorites = new Favorites();
        String sql = "select * from favorites where goodsId = ? and userId = ?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setObject(1,goodsId);
            ps.setObject(2,userId);
            rs = ps.executeQuery();
            favorites = (Favorites) DButil.getRsOne(Favorites.class,rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DButil.close(rs,ps,conn);
        }
        return favorites;
    }

    @Override
    public boolean add(Favorites favorites) {
        return DButil.insert(favorites);
    }

    @Override
    public boolean update(Favorites favorites) {
        return DButil.update(favorites);
    }

    @Override
    public boolean deleteById(Integer id) {
        Connection conn = DButil.getConnection();
        PreparedStatement ps = null;
        String sql = "delete from favorites where favoriteId = ?";
        try {
            ps = conn.prepareStatement(sql);
            ps.setObject(1,id);
            return ps.executeUpdate()>0;
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            DButil.close(null,ps,conn);
        }
        return false;
    }
}
